import axios from "axios";

import config from "@/config";

const TOKEN_INVALID = 'TOKEN认证失败,请重新登录'

const NETWORK_ERROR = '网络请求异常,请稍后重试'

import { Message } from "element-ui";

import router from "@/router";

const service = axios.create({
    baseURL: config.baseApi,
    timeout: 5000
})


service.interceptors.request.use((res)=>{
    let headers = res.headers
    if(!headers.Authoraztion) headers.Authoraztion = 'token'
    return res
},(err)=>{
    return Promise.reject(err)
})


service.interceptors.response.use((res)=>{
    let { code, data, msg } = res.data
    if(code == 200){
        return data
    }else if(code == 40001){
        Message.error(TOKEN_INVALID);
        setTimeout(()=>{
            router.push('/login')
        },1000)
        return Promise.reject(TOKEN_INVALID)
    }else{
        Message.error(NETWORK_ERROR)
        return Promise.reject(NETWORK_ERROR)
    }
},(err)=>{
    return Promise.reject(err)
})



function request(options){
    options.method = options.method || 'get'
    if(options.method.toLowerCase() === 'get'){
        options.params = options.data;
    }
    if(config.env == 'production'){
        service.defaults.baseURL = config.baseApi
    }else{
        service.defaults.baseURL = config.mock ? config.mockApi : config.baseApi
    }
    return service(options)
}


['get', 'post', 'put', 'delete', 'patch'].forEach((item)=>{
    request['get'] = (url, data, options) => {
        return request({
            url,
            data,
            method: item,
            ...options
        })
    }
})


export default request;